#include "tools.h"
#include "getch.h"

//清理输入缓冲区
void clearStdin(void)
{
	stdin->_IO_read_ptr = stdin->_IO_read_end;
}

//获取指令
int getCmd(char start,char end)
{
	puts("----------------");
	printf("请输入指令：");

	int cmd = 0;

	while(true)
	{
		cmd = getch();
		if(cmd >= start && cmd <= end)
		{
			printf("%c\n",cmd);
			break;
		}
	}

	return cmd;
}

//获取字符串
char* getStr(char* str,size_t len)
{
	clearStdin();
	fgets(str,len,stdin);

	size_t size = strlen(str);

	if('\n' == str[size-1])
		str[size-1] = '\0';

	else
		clearStdin();

	return str;
}

//获取密码
char* getPassword(char* password,size_t len,bool flag)
{
	clearStdin();

	size_t index = 0;

	while(index < len)
	{
		char key = getch();

		if(127 == key)
		{
			if(index > 0)
			{
				index--;
				if(flag) printf("\b \b");
			}
			continue;
		}
		if('\n' == key) break;

		password[index++] = key;
	
		if(flag) printf("*");
	}

	password[index] = '\0';
	printf("\n");
	return password;
}

//初始化银行卡号
void initCardNo(const char* path,int cardNo)
{
	if(0 == access(path,F_OK)) return;

	puts(path);

	int fd = open(path,O_WRONLY|O_CREAT|O_TRUNC,0644);

	if(0 > fd)
	{
		printf("%d:%s: open:%m\n",__LINE__,__func__);
		return;
	}

	write(fd,&cardNo,sizeof(cardNo));
	close(fd);
}

//生成一个银行卡号
int createCardNo(const char* path)
{
	int fd = open(path,O_RDWR);

	if(0 > fd)
	{
		perror("open");
		return -1;
	}

	int cardNo = 0;

	read(fd,&cardNo,sizeof(cardNo));
	cardNo = 132400000 + rand()%10000;
	lseek(fd,0,SEEK_SET);
	write(fd,&cardNo,sizeof(cardNo));
	
	return cardNo;

}

//按任意键继续
void anykeyContinue(void)
{
	clearStdin();
	puts("按任意键继续……");
	getch();
}

//结构体转换为字符串
void changeToStr(ClientToServe* ctos,char* buf)
{
	sprintf(buf,"type:%ld bank:%s Idcard:%s password:%s balance:%f isLock:%hhd",ctos->type,ctos->acc.bank,ctos->acc.IdCard,ctos->acc.password,ctos->acc.balance,ctos->acc.isLock);	
}

//字符串转换为结构体
void changeToStruct(char* buf,ClientToServe* ctos)
{
	sscanf(buf,"type:%ld bank:%s Idcard:%s password:%s balance:%f isLock:%hhd",&ctos->type,ctos->acc.bank,ctos->acc.IdCard,ctos->acc.password,&ctos->acc.balance,&ctos->acc.isLock);
}
